from fastapi import FastAPI, Query
from fastapi.middleware.cors import CORSMiddleware
import os

app = FastAPI()

# 配置常量
TYPING_FILE_PATH = "typing.txt"

# 添加CORS中间件，允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

@app.get("/load")
async def load_text(text: str = Query(..., description="要添加到文件的文本")):
    """
    接收文本参数并将其添加到typing.txt文件末尾
    """
    # 确保目录存在（如果文件路径包含目录）
    dir_name = os.path.dirname(TYPING_FILE_PATH)
    if dir_name:  # 只有当目录名非空时才创建目录
        os.makedirs(dir_name, exist_ok=True)
    
    # 将文本添加到typing.txt文件
    with open(TYPING_FILE_PATH, "a", encoding="utf-8") as file:
        file.write(text + "\n")
    
    return {"status": "success", "message": f"文本已添加到{TYPING_FILE_PATH}"}

@app.get("/statistic")
async def get_statistics():
    """
    统计typing.txt文件的字数、行数等信息
    """
    # 如果文件不存在，返回零统计
    if not os.path.exists(TYPING_FILE_PATH):
        return {
            "status": "success",
            "statistics": {
                "total_lines": 0,
                "total_characters": 0,
                "total_characters_no_spaces": 0,
                "total_words": 0,
                "file_exists": False
            }
        }
    
    try:
        with open(TYPING_FILE_PATH, "r", encoding="utf-8") as file:
            content = file.read()
            
            lines = content.split("\n")
            if lines and lines[-1] == "":  # 处理文件末尾的空行
                lines = lines[:-1]
                
            total_lines = len(lines)
            total_characters = len(content)
            total_characters_no_spaces = len(content.replace(" ", "").replace("\n", ""))
            total_words = len(content.split())
            
            return {
                "status": "success",
                "statistics": {
                    "total_lines": total_lines,
                    "total_characters": total_characters,
                    "total_characters_no_spaces": total_characters_no_spaces,
                    "total_words": total_words,
                    "file_exists": True
                }
            }
    except Exception as e:
        return {"status": "error", "message": str(e)}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("index:app", host="0.0.0.0", port=8000, reload=True) 